<template>
	<view class="payment-container">
		<!-- 导航栏 -->
		<u-navbar title="订单支付" :border-bottom="false" :background="{ backgroundColor: '#fff' }">
			<template #left>
				<u-icon name="arrow-left" size="20" @click="goBack"></u-icon>
			</template>
		</u-navbar>
		
		<!-- 支付金额 -->
		<view class="amount-section">
			<view class="amount-info">
				<text class="amount-label">支付金额</text>
				<text class="amount-value">¥{{ paymentAmount }}</text>
			</view>
			<text class="order-info">订单号：{{ orderId }}</text>
		</view>
		
		<!-- 支付方式 -->
		<view class="payment-methods">
			<view class="section-title">选择支付方式</view>
			<view class="method-list">
				<view 
					v-for="method in paymentMethods" 
					:key="method.type"
					@click="selectPaymentMethod(method)"
					class="method-item"
					:class="{ active: selectedMethod.type === method.type }"
				>
					<view class="method-left">
						<image :src="method.icon" class="method-icon"></image>
						<view class="method-info">
							<text class="method-name">{{ method.name }}</text>
							<text class="method-desc">{{ method.description }}</text>
						</view>
					</view>
					<view class="method-right">
						<text v-if="method.balance !== undefined" class="balance">余额：¥{{ method.balance }}</text>
						<u-icon 
							name="checkmark-circle-fill" 
							:color="selectedMethod.type === method.type ? '#667eea' : '#e0e0e0'" 
							size="20"
						></u-icon>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 订单详情 -->
		<view class="order-detail" v-if="orderInfo">
			<view class="section-title">订单详情</view>
			<view class="detail-list">
				<view class="detail-item">
					<text class="detail-label">商品总价</text>
					<text class="detail-value">¥{{ orderInfo.goods_total }}</text>
				</view>
				<view class="detail-item" v-if="orderInfo.delivery_fee > 0">
					<text class="detail-label">配送费</text>
					<text class="detail-value">¥{{ orderInfo.delivery_fee }}</text>
				</view>
				<view class="detail-item" v-if="orderInfo.coupon_discount > 0">
					<text class="detail-label">优惠券</text>
					<text class="detail-value discount">-¥{{ orderInfo.coupon_discount }}</text>
				</view>
				<view class="detail-item total">
					<text class="detail-label">实付金额</text>
					<text class="detail-value total-amount">¥{{ orderInfo.total_amount }}</text>
				</view>
			</view>
		</view>
		
		<!-- 安全提示 -->
		<view class="security-tips">
			<view class="tips-header">
				<u-icon name="shield-checkmark" color="#52c41a" size="18"></u-icon>
				<text class="tips-title">安全保障</text>
			</view>
			<view class="tips-list">
				<text class="tip-item">• 支付过程采用银行级加密技术</text>
				<text class="tip-item">• 资金安全由第三方支付平台保障</text>
				<text class="tip-item">• 支持7天无理由退款</text>
			</view>
		</view>
		
		<!-- 底部支付按钮 -->
		<view class="bottom-pay">
			<view class="pay-info">
				<text class="pay-text">需支付：</text>
				<text class="pay-amount">¥{{ paymentAmount }}</text>
			</view>
			<button 
				class="pay-btn" 
				@click="confirmPayment" 
				:disabled="!selectedMethod.type || paying"
			>
				<text class="pay-btn-text">{{ paying ? '支付中...' : '确认支付' }}</text>
			</button>
		</view>
		
		<!-- 支付密码弹窗 -->
		<u-popup v-model="showPasswordModal" mode="center" border-radius="20">
			<view class="password-modal">
				<view class="modal-header">
					<text class="modal-title">请输入支付密码</text>
					<u-icon name="close" size="20" @click="closePasswordModal"></u-icon>
				</view>
				<view class="modal-content">
					<text class="pay-amount-text">支付金额：¥{{ paymentAmount }}</text>
					<view class="password-input">
						<view 
							v-for="(item, index) in 6" 
							:key="index"
							class="password-dot"
							:class="{ filled: paymentPassword.length > index }"
						>
							<text v-if="paymentPassword.length > index">•</text>
						</view>
					</view>
					<view class="keyboard">
						<view class="keyboard-row" v-for="(row, rowIndex) in keyboard" :key="rowIndex">
							<view 
								v-for="(key, keyIndex) in row" 
								:key="keyIndex"
								@click="inputPassword(key)"
								class="keyboard-key"
								:class="{ delete: key === 'delete', confirm: key === 'confirm' }"
							>
								<u-icon v-if="key === 'delete'" name="backspace" size="20"></u-icon>
								<text v-else-if="key === 'confirm'">确认</text>
								<text v-else>{{ key }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import api from '@/api/index.js'

export default {
	data() {
		return {
			orderId: '',
			paymentAmount: '0.00',
			orderInfo: null,
			selectedMethod: {},
			paying: false,
			showPasswordModal: false,
			paymentPassword: '',
			
			// 支付方式列表
			paymentMethods: [
				{
					type: 'wechat',
					name: '微信支付',
					description: '推荐使用微信支付',
					icon: '/static/icons/wechat-pay.png'
				},
				{
					type: 'alipay',
					name: '支付宝',
					description: '支持花呗分期付款',
					icon: '/static/icons/alipay.png'
				},
				{
					type: 'balance',
					name: '余额支付',
					description: '使用账户余额支付',
					icon: '/static/icons/balance.png',
					balance: '0.00'
				}
			],
			
			// 数字键盘
			keyboard: [
				['1', '2', '3'],
				['4', '5', '6'],
				['7', '8', '9'],
				['', '0', 'delete']
			]
		}
	},
	
	onLoad(options) {
		this.orderId = options.order_id || ''
		this.paymentAmount = options.total || '0.00'
		
		// 设置默认支付方式
		const defaultMethod = options.payment_method || 'wechat'
		this.selectedMethod = this.paymentMethods.find(m => m.type === defaultMethod) || this.paymentMethods[0]
		
		this.loadOrderInfo()
		this.loadUserBalance()
	},
	
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 加载订单信息
		async loadOrderInfo() {
			if (!this.orderId) return
			
			try {
				const res = await api.orderApi.getOrderDetail(this.orderId)
				if (res.r === 0) {
					this.orderInfo = res.data
					this.paymentAmount = res.data.total_amount
				}
			} catch (error) {
				console.error('加载订单信息失败:', error)
			}
		},
		
		// 加载用户余额
		async loadUserBalance() {
			try {
				const res = await api.walletApi.getWalletInfo()
				if (res.r === 0) {
					const balanceMethod = this.paymentMethods.find(m => m.type === 'balance')
					if (balanceMethod) {
						balanceMethod.balance = res.data.balance
					}
				}
			} catch (error) {
				console.error('加载用户余额失败:', error)
			}
		},
		
		// 选择支付方式
		selectPaymentMethod(method) {
			this.selectedMethod = method
		},
		
		// 确认支付
		confirmPayment() {
			if (!this.selectedMethod.type) {
				uni.showToast({
					title: '请选择支付方式',
					icon: 'none'
				})
				return
			}
			
			// 余额支付需要输入密码
			if (this.selectedMethod.type === 'balance') {
				// 检查余额是否足够
				if (parseFloat(this.selectedMethod.balance) < parseFloat(this.paymentAmount)) {
					uni.showToast({
						title: '余额不足',
						icon: 'none'
					})
					return
				}
				this.showPasswordModal = true
			} else {
				// 第三方支付
				this.processPayment()
			}
		},
		
		// 输入支付密码
		inputPassword(key) {
			if (key === 'delete') {
				this.paymentPassword = this.paymentPassword.slice(0, -1)
			} else if (key === 'confirm') {
				if (this.paymentPassword.length === 6) {
					this.processBalancePayment()
				} else {
					uni.showToast({
						title: '请输入6位支付密码',
						icon: 'none'
					})
				}
			} else if (key && this.paymentPassword.length < 6) {
				this.paymentPassword += key
				
				// 自动提交
				if (this.paymentPassword.length === 6) {
					setTimeout(() => {
						this.processBalancePayment()
					}, 300)
				}
			}
		},
		
		// 关闭密码弹窗
		closePasswordModal() {
			this.showPasswordModal = false
			this.paymentPassword = ''
		},
		
		// 处理余额支付
		async processBalancePayment() {
			if (this.paying) return
			
			this.paying = true
			
			try {
				const res = await api.paymentApi.balancePay({
					order_id: this.orderId,
					amount: this.paymentAmount,
					password: this.paymentPassword
				})
				
				if (res.r === 0) {
					this.closePasswordModal()
					this.paymentSuccess(res.data)
				} else {
					uni.showToast({
						title: res.msg || '支付失败',
						icon: 'none'
					})
					this.paymentPassword = ''
				}
			} catch (error) {
				console.error('余额支付失败:', error)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
				this.paymentPassword = ''
			} finally {
				this.paying = false
			}
		},
		
		// 处理第三方支付
		async processPayment() {
			if (this.paying) return
			
			this.paying = true
			
			try {
				const res = await api.paymentApi.createPayment({
					order_id: this.orderId,
					amount: this.paymentAmount,
					payment_method: this.selectedMethod.type
				})
				
				if (res.r === 0) {
					const paymentData = res.data
					
					// 调用对应的支付方式
					if (this.selectedMethod.type === 'wechat') {
						this.wechatPay(paymentData)
					} else if (this.selectedMethod.type === 'alipay') {
						this.alipay(paymentData)
					}
				} else {
					uni.showToast({
						title: res.msg || '支付失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('创建支付失败:', error)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			} finally {
				this.paying = false
			}
		},
		
		// 微信支付
		wechatPay(paymentData) {
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: paymentData.timeStamp,
				nonceStr: paymentData.nonceStr,
				package: paymentData.package,
				signType: paymentData.signType,
				paySign: paymentData.paySign,
				success: (res) => {
					this.paymentSuccess(res)
				},
				fail: (err) => {
					console.error('微信支付失败:', err)
					if (err.errMsg !== 'requestPayment:fail cancel') {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						})
					}
				}
			})
		},
		
		// 支付宝支付
		alipay(paymentData) {
			uni.requestPayment({
				provider: 'alipay',
				orderInfo: paymentData.orderInfo,
				success: (res) => {
					this.paymentSuccess(res)
				},
				fail: (err) => {
					console.error('支付宝支付失败:', err)
					if (err.errMsg !== 'requestPayment:fail cancel') {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						})
					}
				}
			})
		},
		
		// 支付成功
		paymentSuccess(data) {
			uni.showToast({
				title: '支付成功',
				icon: 'success'
			})
			
			// 跳转到支付结果页面
			setTimeout(() => {
				uni.redirectTo({
					url: `/pages/payment/result?order_id=${this.orderId}&status=success`
				})
			}, 1500)
		}
	}
}
</script>

<style scoped>
.payment-container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

/* 支付金额 */
.amount-section {
	background-color: #fff;
	padding: 60rpx 30rpx 40rpx;
	text-align: center;
	margin-bottom: 20rpx;
}

.amount-info {
	margin-bottom: 20rpx;
}

.amount-label {
	font-size: 28rpx;
	color: #666;
	display: block;
	margin-bottom: 10rpx;
}

.amount-value {
	font-size: 72rpx;
	font-weight: bold;
	color: #ff4d4f;
}

.order-info {
	font-size: 24rpx;
	color: #999;
}

/* 支付方式 */
.payment-methods {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 30rpx;
}

.method-list {
	gap: 20rpx;
}

.method-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 25rpx 20rpx;
	border: 2rpx solid #f0f0f0;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	transition: all 0.3s;
}

.method-item.active {
	border-color: #667eea;
	background-color: #f0f2ff;
}

.method-left {
	display: flex;
	align-items: center;
	gap: 20rpx;
	flex: 1;
}

.method-icon {
	width: 60rpx;
	height: 60rpx;
	object-fit: contain;
}

.method-info {
	flex: 1;
}

.method-name {
	font-size: 30rpx;
	color: #333;
	margin-bottom: 5rpx;
	display: block;
}

.method-desc {
	font-size: 24rpx;
	color: #999;
}

.method-right {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	gap: 8rpx;
}

.balance {
	font-size: 24rpx;
	color: #666;
}

/* 订单详情 */
.order-detail {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.detail-list {
	gap: 15rpx;
}

.detail-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 15rpx 0;
}

.detail-item.total {
	border-top: 2rpx solid #f0f0f0;
	padding-top: 20rpx;
	margin-top: 10rpx;
}

.detail-label {
	font-size: 28rpx;
	color: #333;
}

.detail-value {
	font-size: 28rpx;
	color: #333;
}

.detail-value.discount {
	color: #ff4d4f;
}

.detail-value.total-amount {
	font-size: 32rpx;
	font-weight: bold;
	color: #ff4d4f;
}

/* 安全提示 */
.security-tips {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.tips-header {
	display: flex;
	align-items: center;
	gap: 10rpx;
	margin-bottom: 20rpx;
}

.tips-title {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

.tips-list {
	gap: 10rpx;
}

.tip-item {
	font-size: 24rpx;
	color: #666;
	line-height: 1.5;
	margin-bottom: 8rpx;
}

/* 底部支付 */
.bottom-pay {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #fff;
	border-top: 2rpx solid #f0f0f0;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	gap: 30rpx;
	z-index: 100;
}

.pay-info {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.pay-text {
	font-size: 28rpx;
	color: #333;
}

.pay-amount {
	font-size: 36rpx;
	font-weight: bold;
	color: #ff4d4f;
}

.pay-btn {
	flex: 1;
	height: 80rpx;
	background: linear-gradient(135deg, #667eea, #764ba2);
	color: #fff;
	border-radius: 40rpx;
	font-size: 32rpx;
	font-weight: bold;
	border: none;
}

.pay-btn:disabled {
	background: #ccc;
}

.pay-btn-text {
	color: #fff;
}

/* 支付密码弹窗 */
.password-modal {
	width: 600rpx;
	padding: 40rpx;
	background-color: #fff;
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
}

.modal-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.modal-content {
	text-align: center;
}

.pay-amount-text {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 30rpx;
	display: block;
}

.password-input {
	display: flex;
	justify-content: center;
	gap: 15rpx;
	margin-bottom: 40rpx;
}

.password-dot {
	width: 60rpx;
	height: 60rpx;
	border: 2rpx solid #e0e0e0;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 36rpx;
	color: #333;
}

.password-dot.filled {
	border-color: #667eea;
	background-color: #f0f2ff;
}

.keyboard {
	gap: 15rpx;
}

.keyboard-row {
	display: flex;
	justify-content: center;
	gap: 15rpx;
	margin-bottom: 15rpx;
}

.keyboard-key {
	width: 120rpx;
	height: 80rpx;
	background-color: #f5f5f5;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	color: #333;
	transition: all 0.2s;
}

.keyboard-key:active {
	background-color: #e0e0e0;
}

.keyboard-key.delete {
	background-color: #ff4d4f;
	color: #fff;
}

.keyboard-key.confirm {
	background-color: #667eea;
	color: #fff;
}
</style>